import Vue from 'vue'
import server from 'axios'
import Qs from 'qs'
import { LoadingPlugin, ToastPlugin } from 'vux'
Vue.use(LoadingPlugin)
Vue.use(ToastPlugin)

let baseUrl
if (window.location.hostname === 'mstatic.shandjj.com') {
  baseUrl = 'https://activity.shandjj.com'
} else if (window.location.hostname === 'mstatic.sdjjia.com') {
  baseUrl = 'http://activity.sdjjia.com'
} else{
  baseUrl = 'http://activity.shandjj.com'
  // baseUrl = 'http://activity.sdjjia.com'
  // baseUrl = 'http://activity.sdjj.com' 
}
console.log(baseUrl);

var axios = server.create({
  baseURL: baseUrl,
  timeout: 10000,
  transformRequest: [function (data) { return Qs.stringify(data) }]
})

// 添加请求拦截器
// loading过滤处理如果接口url不包含以下名称时，加载loading
axios.interceptors.request.use(function (config) {
  // loading过滤处理
  if (config.url.includes('loading=1')) {
    Vue.$vux.loading.show({ text: '加载中...' })
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  let _url = response.config.url
  let _message = response.data.message
  let _method = response.config.method
  if (response.data.code === 200 || response.data.code === 10000) {
    Vue.$vux.loading.hide()
    return response.data;
  } else {
    Vue.$vux.toast.show({
      type: 'cancel',
      text: response.data.message || response.data.msg || '网络错误，请稍后再试'
    });
    self.errorLogUpload({
      logLevel: 3,
      errType: 22,
      apiError: {
        params: JSON.stringify(response.data),
        uri: location.href,
        apiUri: _url,
        data: JSON.stringify(response.data),
        message: _message,
        method: _method,
        code: 200
      }
    })
    return Promise.reject(response.data)
  }
}, function (error) {
  let config = error.config;
  Vue.$vux.toast.show({
    type: 'cancel',
    text: '请求超时'
  })
  self.errorLogUpload({
    logLevel: 3,
    errType: 22,
    apiError: {
      params: JSON.stringify(config.params),
      uri: location.href,
      apiUri: config.url,
      data: '',
      message: error.toString(),
      method: config.method,
      code: error.request.status
    }
  })
  return Promise.reject(error)
})

export default axios